{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Buffered_Transducer_Inference_with_LCS_Merge.ipynb",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "hrnsEZRzgooE"
      },
      "outputs": [],
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
        "\n\nNOTE: User is responsible for checking the content of datasets and the applicable licenses and determining if suitable for the intended use.\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell.\n",
        "\n",
        "## Install dependencies\n",
        "!pip install wget\n",
        "!apt-get install sox libsndfile1 ffmpeg\n",
        "!pip install text-unidecode\n",
        "!pip install matplotlib>=3.3.2\n",
        "\n",
        "## Install NeMo\n",
        "BRANCH = 'main'\n",
        "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]\n",
        "\n",
        "# Update numba and restart (this is required to update internal numba version of Colab)\n",
        "\n",
        "# In a conda environment, you would use the following command\n",
        "# Update Numba to > 0.54\n",
        "# conda install -c conda-forge numba>=0.54\n",
        "# or\n",
        "# conda update -c conda-forge numba>=0.54\n",
        "\n",
        "# For pip based environments,\n",
        "# Update Numba to > 0.54\n",
        "import os\n",
        "import signal\n",
        "\n",
        "!pip install --upgrade numba\n",
        "\n",
        "# This will kill the kernel, click next cell to import the latest numba\n",
        "os.kill(os.getpid(), signal.SIGKILL)"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Buffered Transducer evaluation with Longest Common Subsequence Merge\n",
        "\n",
        "In the [Buffered Transducer Inference](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/asr/Buffered_Transducer_Inference.ipynb) tutorial, we discussed how we could perform Streaming/Buffered inference with Transducer models by using a technique which we term as `\"Middle Token\" selection` from a buffer.\n",
        "\n",
        "In this notebook, we will perform buffered ASR speech recognition and utilize another algorithm to merge buffers during inference. We term this method as the `\"Longest Common Subsequence\" (LCS) Merge` algorithm.\n",
        "\n",
        "While the `Middle Token` algorithm works well in general, it is not a perfect merge algorithm and can make mistakes. We, therefore, compare against the `LCS Merge` algorithm and discuss the merits of both approaches. \n",
        "\n",
        "-----\n",
        "\n",
        "You may use this script [ASR Chunked Streaming Inference](https://github.com/NVIDIA/NeMo/blob/stable/examples/asr/asr_chunked_inference/rnnt/speech_to_text_buffered_infer_rnnt.py) to transcribe long audio files with Transducer models as well as experiment with both merge algorithms. \n"
      ],
      "metadata": {
        "id": "cPuPBSU0ioJO"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "------\n",
        "\n",
        "**Note**: It is highly recommended to review the ``Streaming ASR`` tutorial for a good overview of how streaming/buffered inference works for CTC models and the underlying motivation of streaming ASR itself.\n",
        "\n",
        "------"
      ],
      "metadata": {
        "id": "ylQ3GwvX-n7R"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Prepare the dataset\n",
        "\n",
        "We will reuse the Librispeech dev-clean subset of [Mini Librispeech](https://www.openslr.org/31/). This time, we will not concatenate the audio segments but simply evaluate them in buffered mode over all the audio samples.\n",
        "\n",
        "**Note**: Conformer inference over the entire dev set will take an exorbitant amount of time on the CPU. We recommend the use of GPU for this tutorial."
      ],
      "metadata": {
        "id": "2eDAsjyCi3lc"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Download and prepare Mini Librispeech"
      ],
      "metadata": {
        "id": "fBYvC3lyjM7O"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Prepare dataset and manifest for Libripeech Dev Clean subset.\n",
        "import os\n",
        "\n",
        "if not os.path.exists(\"scripts/get_librispeech_data.py\"):\n",
        "  !wget -P scripts/ https://raw.githubusercontent.com/NVIDIA/NeMo/stable/scripts/dataset_processing/get_librispeech_data.py\n",
        "\n",
        "# If something goes wrong during data processing, un-comment the following line to delete the cached dataset \n",
        "# !rm -rf datasets/mini-dev-clean\n",
        "!mkdir -p datasets/mini-dev-clean\n",
        "\n",
        "!python scripts/get_librispeech_data.py \\\n",
        "  --data_root \"datasets/mini-dev-clean/\" \\\n",
        "  --data_sets dev_clean_2 \\\n",
        "  --num_workers=10 \\\n",
        "  --log"
      ],
      "metadata": {
        "cellView": "form",
        "id": "LBiTnpz6iket"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "manifest = os.path.join(os.getcwd(), \"datasets/mini-dev-clean/dev_clean_2.json\")\n",
        "print(\"Manifest path :\", manifest)"
      ],
      "metadata": {
        "id": "KHcy1Jbx8d9V"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Prepare the model\n",
        "\n",
        "We will use the same Conformer Transducer model used in the `Buffered Transducer Inference` tutorial, which will provide a fair comparison between the proposed merge algorithms described here."
      ],
      "metadata": {
        "id": "8g61qBwgkHiw"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import torch\n",
        "import nemo.collections.asr as nemo_asr\n",
        "import contextlib\n",
        "import gc\n",
        "\n",
        "# Helper for torch amp autocast\n",
        "if torch.cuda.is_available():\n",
        "    autocast = torch.cuda.amp.autocast\n",
        "else:\n",
        "    @contextlib.contextmanager\n",
        "    def autocast():\n",
        "        print(\"AMP was not available, using FP32!\")\n",
        "        yield\n",
        "\n",
        "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
        "device"
      ],
      "metadata": {
        "id": "j9UHfsR1j-uf"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "pretrained_model_name = \"stt_en_conformer_transducer_large\""
      ],
      "metadata": {
        "id": "CzkoimqKl07U"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "# Clear up memory\n",
        "torch.cuda.empty_cache()\n",
        "gc.collect()\n",
        "model = nemo_asr.models.EncDecRNNTBPEModel.from_pretrained(pretrained_model_name, map_location=device)\n",
        "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
        "# device = 'cpu'  # You can transcribe even longer samples on the CPU, though it will take much longer !\n",
        "model = model.to(device)\n",
        "model.freeze()"
      ],
      "metadata": {
        "id": "0LjtehkvlvKE"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Longest Common Subsequence Merge\n",
        "\n",
        "Below, we construct the `Longest Common Subsequence Merge` algorithm to merge two consecutive transcript buffers - termed `i-1`th and `i`th buffers. The concept is similar to the work discussed in the paper [Partially Overlapped Inference for Long-Form Speech Recognition](https://ieeexplore.ieee.org/document/9414941) but operates on the notion of subword buffers rather than character tokens.\n",
        "\n",
        "In contrast to the `Middle Token` algorithm, which utilizes certain seconds of both past and future context in order to determine the \"middle tokens\" for that current buffer, the `LCS Merge` algorithm merges only consecutive buffers by selecting the overlap between the end of the `i-1`th buffer and the beginning of the `i`th buffer sub-word tokens, then removing the overlapped tokens from the `i`th buffer.\n",
        "\n",
        "While the idea is simple, since the same text can be represented by a different combination of sub-words, some additional expansion steps must be accounted for to account for imperfect alignment between two buffers."
      ],
      "metadata": {
        "id": "OPZqcbNEnRkI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "### Utility Functions ###\n",
        "def print_alignment(alignment):\n",
        "    \"\"\"\n",
        "    Print an alignment matrix of the shape (m + 1, n + 1)\n",
        "\n",
        "    Args:\n",
        "        alignment: An integer alignment matrix of shape (m + 1, n + 1)\n",
        "    \"\"\"\n",
        "    m = len(alignment)\n",
        "    if m > 0:\n",
        "        n = len(alignment[0])\n",
        "        for i in range(m):\n",
        "            for j in range(n):\n",
        "                if j == 0:\n",
        "                    print(f\"{i:4d} |\", end=\" \")\n",
        "                print(f\"{alignment[i][j]}\", end=\" \")\n",
        "            print()\n",
        "\n",
        "\n",
        "def write_lcs_alignment_to_pickle(alignment, filepath, extras=None):\n",
        "    \"\"\"\n",
        "    Writes out the LCS alignment to a file, along with any extras provided.\n",
        "\n",
        "    Args:\n",
        "        alignment: An alignment matrix of shape [m + 1, n + 1]\n",
        "        filepath: str filepath\n",
        "        extras: Optional dictionary of items to preserve.\n",
        "    \"\"\"\n",
        "    if extras is None:\n",
        "        extras = {}\n",
        "\n",
        "    extras['alignment'] = alignment\n",
        "    torch.save(extras, filepath)"
      ],
      "metadata": {
        "id": "pEPLZyJP_zx2"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Algorithm overview\n",
        "\n",
        "At a high level, the algorithm can be decomposed into the following steps - \n",
        "\n",
        "1. Construct Longest Common Subsequence suffix matrix for initial alignment of text from old and new buffers.\n",
        "2. Detect partial alignment or complete alignment.\n",
        "3. If partial alignment, Loop over LCS suffix matrix to perform a dual objective search: <br>\n",
        "  3.1 Find largest score for LCS at the leftmost target axis: <br>\n",
        "      \n",
        "      This fixed cases where intermediate tokens are an exact match to subsequent buffer getting deleted (causing a larger merge than expected and incurring a high deletion rate). <br>\n",
        "\n",
        "  3.2 Then perform greedy expansion of this suffix: <br>\n",
        "\n",
        "      Perform a loop descending towards the end of the suffix matrix, expanding the search space. <br>\n",
        "      Limit expansion width such that only one additional token can escape per step (prevent extremely far away tokens from the current position from being used for expanded) <br>\n",
        "5. Perform a backward trace of the LCS suffix matrix to find detached sections to know the beginning index of slice and length of slice.\n",
        "6. Finally, check that beginning index of slice < max number of buffer chunks; if true, then slice off new buffer\n",
        " "
      ],
      "metadata": {
        "id": "EwPrhOP2_7D2"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Minimum number of tokens required to assign a LCS merge step, otherwise ignore and\n",
        "# select all i-1 and ith buffer tokens to merge.\n",
        "MIN_MERGE_SUBSEQUENCE_LEN = 1\n",
        "\n",
        "### LCS algorithm ###\n",
        "def longest_common_subsequence_merge(X, Y, filepath=None):\n",
        "    \"\"\"\n",
        "    Longest Common Subsequence merge algorithm for aligning two consecutive buffers.\n",
        "\n",
        "    Base alignment construction algorithm is Longest Common Subsequence (referred to as LCS hear after)\n",
        "\n",
        "    LCS Merge algorithm looks at two chunks i-1 and i, determines the aligned overlap at the\n",
        "    end of i-1 and beginning of ith chunk, and then clips the subsegment of the ith chunk.\n",
        "\n",
        "    Assumption is that the two chunks are consecutive chunks, and there exists at least small overlap acoustically.\n",
        "\n",
        "    It is a sub-word token merge algorithm, operating on the abstract notion of integer ids representing the subword ids.\n",
        "    It is independent of text or character encoding.\n",
        "\n",
        "    Since the algorithm is merge based, and depends on consecutive buffers, the very first buffer is processed using\n",
        "    the \"middle tokens\" algorithm.\n",
        "\n",
        "    It requires a delay of some number of tokens such that:\n",
        "        lcs_delay = math.floor(((total_buffer_in_secs - chunk_len_in_sec)) / model_stride_in_secs)\n",
        "\n",
        "    Total cost of the model is O(m_{i-1} * n_{i}) where (m, n) represents the number of subword ids of the buffer.\n",
        "\n",
        "    Args:\n",
        "        X: The subset of the previous chunk i-1, sliced such X = X[-(lcs_delay * max_steps_per_timestep):]\n",
        "            Therefore there can be at most lcs_delay * max_steps_per_timestep symbols for X, preserving computation.\n",
        "        Y: The entire current chunk i.\n",
        "        filepath: Optional filepath to save the LCS alignment matrix for later introspection.\n",
        "\n",
        "    Returns:\n",
        "        A tuple containing -\n",
        "            - i: Start index of alignment along the i-1 chunk.\n",
        "            - j: Start index of alignment along the ith chunk.\n",
        "            - slice_len: number of tokens to slice off from the ith chunk.\n",
        "        The LCS alignment matrix itself (shape m + 1, n + 1)\n",
        "    \"\"\"\n",
        "    # LCSuff is the table with zero\n",
        "    # value initially in each cell\n",
        "    m = len(X)\n",
        "    n = len(Y)\n",
        "    LCSuff = [[0 for k in range(n + 1)] for l in range(m + 1)]\n",
        "\n",
        "    # To store the length of\n",
        "    # longest common substring\n",
        "    result = 0\n",
        "    result_idx = [0, 0, 0]  # Contains (i, j, slice_len)\n",
        "\n",
        "    # Following steps to build\n",
        "    # LCSuff[m+1][n+1] in bottom up fashion\n",
        "    for i in range(m + 1):\n",
        "        for j in range(n + 1):\n",
        "            if i == 0 or j == 0:\n",
        "                LCSuff[i][j] = 0\n",
        "            elif X[i - 1] == Y[j - 1]:\n",
        "                LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1\n",
        "\n",
        "                if result <= LCSuff[i][j]:\n",
        "                    result = LCSuff[i][j]\n",
        "                    result_idx = [i, j, result]\n",
        "\n",
        "            else:\n",
        "                LCSuff[i][j] = 0\n",
        "\n",
        "    # Check if perfect alignment was found or not\n",
        "    # Perfect alignment is found if :\n",
        "    # Longest common subsequence extends to the final row of of the old buffer\n",
        "    # This means that there exists a diagonal LCS backtracking to the beginning of the new buffer\n",
        "    i, j = result_idx[0:2]\n",
        "    is_complete_merge = i == m\n",
        "\n",
        "    # Perfect alignment was found, slice eagerly\n",
        "    if is_complete_merge:\n",
        "        length = result_idx[-1]\n",
        "\n",
        "        # In case the LCS was incomplete - missing a few tokens at the beginning\n",
        "        # Perform backtrack to find the origin point of the slice (j) and how many tokens should be sliced\n",
        "        while length >= 0 and i > 0 and j > 0:\n",
        "            # Alignment exists at the required diagonal\n",
        "            if LCSuff[i - 1][j - 1] > 0:\n",
        "                length -= 1\n",
        "                i, j = i - 1, j - 1\n",
        "\n",
        "            else:\n",
        "                # End of longest alignment\n",
        "                i, j, length = i - 1, j - 1, length - 1\n",
        "                break\n",
        "\n",
        "    else:\n",
        "        # Expand hypothesis to catch partial mismatch\n",
        "\n",
        "        # There are 3 steps for partial mismatch in alignment\n",
        "        # 1) Backward search for leftmost LCS\n",
        "        # 2) Greedy expansion of leftmost LCS to the right\n",
        "        # 3) Backtrack final leftmost expanded LCS to find origin point of slice\n",
        "\n",
        "        # (1) Backward search for Leftmost LCS\n",
        "        # This is required for cases where multiple common subsequences exist\n",
        "        # We only need to select the leftmost one - since that corresponds\n",
        "        # to the last potential subsequence that matched with the new buffer.\n",
        "        # If we just chose the LCS (and not the leftmost LCS), then we can potentially\n",
        "        # slice off major sections of text which are repeated between two overlapping buffers.\n",
        "\n",
        "        # backward linear search for leftmost j with longest subsequence\n",
        "        max_j = 0\n",
        "        max_j_idx = n\n",
        "\n",
        "        i_partial = m  # Starting index of i for partial merge\n",
        "        j_partial = -1  # Index holder of j for partial merge\n",
        "        j_skip = 0  # Number of tokens that were skipped along the diagonal\n",
        "        slice_count = 0  # Number of tokens that should be sliced\n",
        "\n",
        "        # Select leftmost LCS\n",
        "        for i_idx in range(m, -1, -1):  # start from last timestep of old buffer\n",
        "            for j_idx in range(0, n + 1):  # start from first token from new buffer\n",
        "                # Select the longest LCSuff, while minimizing the index of j (token index for new buffer)\n",
        "                if LCSuff[i_idx][j_idx] > max_j and j_idx <= max_j_idx:\n",
        "                    max_j = LCSuff[i_idx][j_idx]\n",
        "                    max_j_idx = j_idx\n",
        "\n",
        "                    # Update the starting indices of the partial merge\n",
        "                    i_partial = i_idx\n",
        "                    j_partial = j_idx\n",
        "\n",
        "        # EARLY EXIT (if max subsequence length <= MIN merge length)\n",
        "        # Important case where there is long silence\n",
        "        # The end of one buffer will have many blank tokens, the beginning of new buffer may have many blank tokens\n",
        "        # As such, LCS will potentially be from the region of actual tokens.\n",
        "        # This can be detected as the max length of the suffix in LCS\n",
        "        # If this max length of the leftmost suffix is less than some margin, avoid slicing all together.\n",
        "        if max_j <= MIN_MERGE_SUBSEQUENCE_LEN:\n",
        "            # If the number of partiial tokens to be deleted are less than the minimum,\n",
        "            # dont delete any tokens at all.\n",
        "\n",
        "            i = i_partial\n",
        "            j = 0\n",
        "            result_idx[-1] = 0\n",
        "\n",
        "        else:\n",
        "            # Some valid long partial alignment was found\n",
        "            # (2) Expand this alignment along the diagonal *downwards* towards the end of the old buffer\n",
        "            # such that i_partial = m + 1.\n",
        "            # This is a common case where due to LSTM state or reduced buffer size, the alignment breaks\n",
        "            # in the middle but there are common subsequences between old and new buffers towards the end\n",
        "            # We can expand the current leftmost LCS in a diagonal manner downwards to include such potential\n",
        "            # merge regions.\n",
        "\n",
        "            # Expand current partial subsequence with co-located tokens\n",
        "            i_temp = i_partial + 1  # diagonal next i\n",
        "            j_temp = j_partial + 1  # diagonal next j\n",
        "\n",
        "            j_exp = 0  # number of tokens to expand along the diagonal\n",
        "            j_skip = 0  # how many diagonals didn't have the token. Incremented by 1 for every row i\n",
        "\n",
        "            for i_idx in range(i_temp, m + 1):  # walk from i_partial + 1 => m + 1\n",
        "                j_any_skip = 0  # If the diagonal element at this location is not found, set to 1\n",
        "                # j_any_skip expands the search space one place to the right\n",
        "                # This allows 1 diagonal misalignment per timestep i (and expands the search for the next timestep)\n",
        "\n",
        "                # walk along the diagonal corresponding to i_idx, plus allowing diagonal skips to occur\n",
        "                # diagonal elements may not be aligned due to ASR model predicting\n",
        "                # incorrect token in between correct tokens\n",
        "                for j_idx in range(j_temp, j_temp + j_skip + 1):\n",
        "                    if j_idx < n + 1:\n",
        "                        if LCSuff[i_idx][j_idx] == 0:\n",
        "                            j_any_skip = 1\n",
        "                        else:\n",
        "                            j_exp = 1 + j_skip + j_any_skip\n",
        "\n",
        "                # If the diagonal element existed, dont expand the search space,\n",
        "                # otherwise expand the search space 1 token to the right\n",
        "                j_skip += j_any_skip\n",
        "\n",
        "                # Move one step to the right for the next diagonal j corresponding to i\n",
        "                j_temp += 1\n",
        "\n",
        "            # reset j_skip, augment j_partial with expansions\n",
        "            j_skip = 0\n",
        "            j_partial += j_exp\n",
        "\n",
        "            # (3) Given new leftmost j_partial with expansions, backtrack the partial alignments\n",
        "            # counting how many diagonal skips occurred to compute slice length\n",
        "            # as well as starting point of slice.\n",
        "\n",
        "            # Partial backward trace to find start of slice\n",
        "            while i_partial > 0 and j_partial > 0:\n",
        "                if LCSuff[i_partial][j_partial] == 0:\n",
        "                    # diagonal skip occurred, move j to left 1 extra time\n",
        "                    j_partial -= 1\n",
        "                    j_skip += 1\n",
        "\n",
        "                if j_partial > 0:\n",
        "                    # If there are more steps to be taken to the left, slice off the current j\n",
        "                    # Then loop for next (i, j) diagonal to the upper left\n",
        "                    slice_count += 1\n",
        "                    i_partial -= 1\n",
        "                    j_partial -= 1\n",
        "\n",
        "            # Recompute total slice length as slice count along diagonal\n",
        "            # plus the number of diagonal skips\n",
        "            i = max(0, i_partial)\n",
        "            j = max(0, j_partial)\n",
        "            result_idx[-1] = slice_count + j_skip\n",
        "\n",
        "    # Set the value of i and j\n",
        "    result_idx[0] = i\n",
        "    result_idx[1] = j\n",
        "\n",
        "    if filepath is not None:\n",
        "        extras = {\n",
        "            \"is_complete_merge\": is_complete_merge,\n",
        "            \"X\": X,\n",
        "            \"Y\": Y,\n",
        "            \"slice_idx\": result_idx,\n",
        "        }\n",
        "        write_lcs_alignment_to_pickle(LCSuff, filepath=filepath, extras=extras)\n",
        "        print(\"Wrote alignment to :\", filepath)\n",
        "\n",
        "    return result_idx, LCSuff\n",
        "\n",
        "\n"
      ],
      "metadata": {
        "id": "AOBFADPdoJc8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Merge Overview\n",
        "\n",
        "Now that the LCS suffix matrix has been backtracked to obtain the starting index of the slice and the length of the slice, the merge algorithm has a simple task of simply slicing off a portion of the new buffer.\n",
        "\n",
        "There are a few cases when merging buffers, discussed below : \n",
        "\n",
        "1. If there is no future context provided (i.e., chunk size == buffer size), then there is no need to merge tokens since there is no overlap possible. Then, concatenate all tokens emitted from the previous and current buffers.\n",
        "\n",
        "2. For the first buffer, since there isn't a \"previous buffer\", utilize the `Middle Token` algorithm to select tokens of the first buffer and do not perform LCS merge.\n",
        "\n",
        "3. To reduce the quadratic cost of the LCS suffix matrix computation, we pre-slice a subset of the tokens by the limit of `lcs_delay * max_symbols_per_step`. \n",
        "\n",
        "  > Since $lcs\\_delay = \\frac{total\\_buffer\\_in\\_seconds \\: - \\: chunk\\_size\\_in\\_sec}{model\\_stride\\_in\\_sec}$, it is usually just a small amount such as 10-20 time steps. Overall, this limits the number of tokens in the previous buffer to close to 100 or so tokens, thereby limiting the cost of the LCS suffix matrix.\n",
        "\n",
        "4. Compute the start index and slice length using the computed LCS merge.\n",
        "\n",
        "5. Slice off the new data (`i`th chunk)\n",
        "\n",
        "6. Merge the previous and current subset of the chunk and return the merged buffer."
      ],
      "metadata": {
        "id": "QeCGszfO_5cI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def lcs_alignment_merge_buffer(buffer, data, delay, model, max_steps_per_timestep: int = 5, filepath: str = None):\n",
        "    \"\"\"\n",
        "    Merges the new text from the current frame with the previous text contained in the buffer.\n",
        "\n",
        "    The alignment is based on a Longest Common Subsequence algorithm, with some additional heuristics leveraging\n",
        "    the notion that the chunk size is >= the context window. In case this assumptio is violated, the results of the merge\n",
        "    will be incorrect (or at least obtain worse WER overall).\n",
        "    \"\"\"\n",
        "    # If delay timesteps is 0, that means no future context was used. Simply concatenate the buffer with new data.\n",
        "    if delay < 1:\n",
        "        buffer += data\n",
        "        return buffer\n",
        "\n",
        "    # If buffer is empty, simply concatenate the buffer and data.\n",
        "    if len(buffer) == 0:\n",
        "        buffer += data\n",
        "        return buffer\n",
        "\n",
        "    # Prepare a subset of the buffer that will be LCS Merged with new data\n",
        "    search_size = int(delay * max_steps_per_timestep)\n",
        "    buffer_slice = buffer[-search_size:]\n",
        "\n",
        "    # Perform LCS Merge\n",
        "    lcs_idx, lcs_alignment = longest_common_subsequence_merge(buffer_slice, data, filepath=filepath)\n",
        "\n",
        "    # Slice off new data\n",
        "    # i, j, slice_len = lcs_idx\n",
        "    slice_idx = lcs_idx[1] + lcs_idx[-1]  # slice = j + slice_len\n",
        "    data = data[slice_idx:]\n",
        "\n",
        "    # Concat data to buffer\n",
        "    buffer += data\n",
        "    return buffer"
      ],
      "metadata": {
        "id": "_6r78fEm_48d"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# LCS Merge algorithm as a basis for Buffered ASR\n",
        "\n",
        "Next, let us extend the previous `BatchedFrameASRRNNT` codebase for Buffered Transducer to incorporate the new merge algorithm.\n",
        "\n",
        "We will note that the vast majority of the code remains unchanged - only the `transcribe` function has been changed to utilize the new merge algorithm."
      ],
      "metadata": {
        "id": "Bz31XOhLqu3z"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.collections.asr.parts.utils import streaming_utils\n",
        "from torch.utils.data import DataLoader\n",
        "\n",
        "\n",
        "class LongestCommonSubsequenceBatchedFrameASRRNNT(streaming_utils.BatchedFrameASRRNNT):\n",
        "    \"\"\"\n",
        "    Implements a token alignment algorithm for text alignment instead of middle token alignment.\n",
        "\n",
        "    For more detail, read the docstring of longest_common_subsequence_merge().\n",
        "    \"\"\"\n",
        "\n",
        "    def __init__(self, asr_model, frame_len=1.6, total_buffer=4.0,\n",
        "        batch_size=4, max_steps_per_timestep: int = 5, stateful_decoding: bool = False, \n",
        "        alignment_basepath: str = None,\n",
        "    ):\n",
        "        '''\n",
        "        Args:\n",
        "            asr_model: An RNNT model.\n",
        "            frame_len: frame's duration, seconds.\n",
        "            total_buffer: duration of total audio chunk size, in seconds.\n",
        "            batch_size: Number of independent audio samples to process at each step.\n",
        "            max_steps_per_timestep: Maximum number of tokens (u) to process per acoustic timestep (t).\n",
        "            stateful_decoding: Boolean whether to enable stateful decoding for preservation of state across buffers.\n",
        "            alignment_basepath: Str path to a directory where alignments from LCS will be preserved for later analysis.\n",
        "        '''\n",
        "        super().__init__(asr_model, frame_len, total_buffer, batch_size, max_steps_per_timestep, stateful_decoding)\n",
        "        self.sample_offset = 0\n",
        "        self.lcs_delay = -1\n",
        "        self.alignment_basepath = alignment_basepath\n",
        "\n",
        "    def transcribe(\n",
        "        self, tokens_per_chunk: int, delay: int,\n",
        "    ):\n",
        "        if self.lcs_delay < 0:\n",
        "            raise ValueError(\n",
        "                \"Please set LCS Delay values as `(buffer_duration - chunk_duration) / model_stride_in_secs`\"\n",
        "            )\n",
        "\n",
        "        self.infer_logits()\n",
        "\n",
        "        self.unmerged = [[] for _ in range(self.batch_size)]\n",
        "        for idx, alignments in enumerate(self.all_alignments):\n",
        "\n",
        "            signal_end_idx = self.frame_bufferer.signal_end_index[idx]\n",
        "            if signal_end_idx is None:\n",
        "                raise ValueError(\"Signal did not end\")\n",
        "\n",
        "            for a_idx, alignment in enumerate(alignments):\n",
        "\n",
        "                # Middle token algorithm for the first chunk\n",
        "                if a_idx == 0:\n",
        "                    alignment = alignment[len(alignment) - 1 - delay :]\n",
        "                    ids, toks = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id)\n",
        "\n",
        "                    if len(ids) > 0:\n",
        "                        self.unmerged[idx] = streaming_utils.inplace_buffer_merge(\n",
        "                            self.unmerged[idx], ids, delay, model=self.asr_model,\n",
        "                        )\n",
        "\n",
        "                else:\n",
        "                    # Use LCS Merge algorithm for remaining chunks\n",
        "                    ids, toks = self._alignment_decoder(alignment, self.asr_model.tokenizer, self.blank_id)\n",
        "                    if len(ids) > 0 and a_idx < signal_end_idx:\n",
        "                        \n",
        "                        # Preserve the LCS alignments if a alignment path was provided\n",
        "                        if self.alignment_basepath is not None:\n",
        "                            basepath = self.alignment_basepath\n",
        "                            sample_offset = self.sample_offset + idx\n",
        "                            alignment_offset = a_idx\n",
        "                            path = os.path.join(basepath, str(sample_offset))\n",
        "\n",
        "                            os.makedirs(path, exist_ok=True)\n",
        "                            path = os.path.join(path, \"alignment_\" + str(alignment_offset) + '.pt')\n",
        "\n",
        "                            filepath = path\n",
        "                        else:\n",
        "                            filepath = None \n",
        "\n",
        "                        # Perform LCS merge\n",
        "                        self.unmerged[idx] = lcs_alignment_merge_buffer(\n",
        "                            self.unmerged[idx],\n",
        "                            ids,\n",
        "                            self.lcs_delay,\n",
        "                            model=self.asr_model,\n",
        "                            max_steps_per_timestep=self.max_steps_per_timestep,\n",
        "                            filepath=filepath,\n",
        "                        )\n",
        "\n",
        "        output = []\n",
        "        for idx in range(self.batch_size):\n",
        "            output.append(self.greedy_merge(self.unmerged[idx]))\n",
        "        return output\n"
      ],
      "metadata": {
        "id": "wNgmc68nl1Ri"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Comparing \"Middle Token\" and \"LCS Merge\"\n",
        "\n",
        "While we propose the two algorithms - `Middle Token` and `LCS Merge`, we would recommend using either algorithm in the appropriate circumstances. The `Middle Token` algorithm performs well in general, and its mistakes are often fewer than the `LCS Merge` algorithm but requires future context, which may increase latency by a small amount. There are also cases where `LCS Merge` may select better alignments and result in slightly better scores for some audio samples.\n",
        "\n",
        "In general, we propose these approaches to discuss further and research merge algorithms that show some trade-off between latency and accuracy."
      ],
      "metadata": {
        "id": "0fmD9goyrmEb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Change Decoding Strategy for Buffered Inference\n",
        "# Change Decoding Config\n",
        "from omegaconf import OmegaConf, open_dict\n",
        "\n",
        "decoding_cfg = model.cfg.decoding\n",
        "with open_dict(decoding_cfg):\n",
        "    decoding_cfg.strategy = \"greedy_batch\"\n",
        "    decoding_cfg.preserve_alignments = True  # required to compute the middle token for transducers.\n",
        "    decoding_cfg.fused_batch_size = -1  # temporarily stop fused batch during inference.\n",
        "\n",
        "model.change_decoding_strategy(decoding_cfg)"
      ],
      "metadata": {
        "cellView": "form",
        "id": "FlIGOc_yl4aQ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Helper methods to transcribe audio in buffered mode\n",
        "\n",
        "import tqdm\n",
        "import math\n",
        "\n",
        "def transcribe_buffers(asr_decoder, audio_filepaths, chunk_len_in_secs, buffer_len_in_secs, model_stride):\n",
        "  model.freeze()\n",
        "  model_stride_in_secs = asr_decoder.asr_model.cfg.preprocessor.window_stride * model_stride\n",
        "  tokens_per_chunk = math.ceil(chunk_len_in_secs / model_stride_in_secs)\n",
        "  mid_delay = math.ceil((chunk_len_in_secs + (buffer_len_in_secs - chunk_len_in_secs) / 2) / model_stride_in_secs)\n",
        "  lcs_delay = math.floor(((buffer_len_in_secs - chunk_len_in_secs)) / model_stride_in_secs)\n",
        "\n",
        "  hyps = []\n",
        "  batch_size = asr_decoder.batch_size \n",
        "\n",
        "  with torch.inference_mode():\n",
        "    with torch.cuda.amp.autocast():\n",
        "      batch = []\n",
        "      asr_decoder.sample_offset = 0\n",
        "      asr_decoder.lcs_delay = lcs_delay\n",
        "\n",
        "      for idx in tqdm.tqdm(range(len(audio_filepaths)), desc='Sample:', total=len(audio_filepaths)):\n",
        "          batch.append(audio_filepaths[idx],)\n",
        "\n",
        "          if len(batch) == batch_size:\n",
        "              audio_files = [sample for sample in batch]\n",
        "\n",
        "              asr_decoder.reset()\n",
        "              asr_decoder.read_audio_file(audio_files, mid_delay, model_stride_in_secs)\n",
        "              hyp_list = asr_decoder.transcribe(tokens_per_chunk, mid_delay)\n",
        "              hyps.extend(hyp_list)\n",
        "\n",
        "              batch.clear()\n",
        "              asr_decoder.sample_offset += batch_size\n",
        "\n",
        "      if len(batch) > 0:\n",
        "          asr_decoder.batch_size = len(batch)\n",
        "          asr_decoder.frame_bufferer.batch_size = len(batch)\n",
        "          asr_decoder.reset()\n",
        "\n",
        "          audio_files = [sample for sample in batch]\n",
        "          asr_decoder.read_audio_file(audio_files, mid_delay, model_stride_in_secs)\n",
        "          hyp_list = asr_decoder.transcribe(tokens_per_chunk, mid_delay)\n",
        "          hyps.extend(hyp_list)\n",
        "\n",
        "          batch.clear()\n",
        "          asr_decoder.sample_offset += len(batch)\n",
        "  \n",
        "  print(\"Finished transcribing audio files\")\n",
        "  return hyps"
      ],
      "metadata": {
        "id": "laPBH4eJsiJk",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Select data subset\n",
        "\n",
        "On the GPU, it would take a few minutes to perform inference for the entire dataset, but on the CPU, it would take quite a long time. While the defaults will exist for the whole dataset, if only the CPU is available for some reason, we encourage you to subsample the dataset."
      ],
      "metadata": {
        "id": "csSNtwziubeM"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Manifest helper\n",
        "import json\n",
        "import numpy as np\n",
        "from nemo.collections.asr.parts.utils.manifest_utils import read_manifest\n",
        "\n",
        "\n",
        "def subset_manifest(manifest, num_samples):\n",
        "  rng = np.random.RandomState(seed=0)\n",
        "  num_samples = min(len(manifest), num_samples)\n",
        "\n",
        "  if num_samples < len(manifest):\n",
        "    ids = rng.choice(np.arange(len(manifest)), size=num_samples, replace=False)\n",
        "    ids = ids.tolist()\n",
        "  else:\n",
        "    ids = np.arange(len(manifest)).tolist()\n",
        "\n",
        "  sub_manifest = []\n",
        "  for idx in ids:\n",
        "    sub_manifest.append(manifest[idx])\n",
        "  \n",
        "  print(f\"Prepared subset manifest with {len(sub_manifest)} samples.\")\n",
        "  return sub_manifest"
      ],
      "metadata": {
        "cellView": "form",
        "id": "QoZ0fG8zuf5E"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "manifest_data = read_manifest(manifest)\n",
        "print(f\"Read {len(manifest_data)} samples from manifest {manifest}\")"
      ],
      "metadata": {
        "id": "I8dnQRL6umrO"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "num_samples = len(manifest_data)\n",
        "\n",
        "#########################################################\n",
        "sub_manifest = subset_manifest(manifest_data, num_samples)\n",
        "audio_filepaths = [sample['audio_filepath'] for sample in sub_manifest]\n",
        "ground_texts = [sample['text'] for sample in sub_manifest]"
      ],
      "metadata": {
        "id": "zZOTSFHsuswe"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Buffered Inference arguments\n",
        "\n",
        "Below we detail some critical arguments for buffered transducer inference. Note that the primary difference between streaming and buffered inference would be the chunk length, with larger values contributing to a lower word error rate but higher latency. "
      ],
      "metadata": {
        "id": "GURl8G2Bwlad"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "chunk_len_in_secs: float = 8.0\n",
        "context_len_in_secs: float = 1.0\n",
        "model_stride: int = 4  # 4 for conformers, 8 for contextnet\n",
        "\n",
        "batch_size: int = 64  # Select a low value for CPU such as 4 or 8.\n",
        "lcs_alignments_path = os.path.join(os.getcwd(), \"lcs_alignments\")\n",
        "max_steps_per_timestep: int = model.cfg.decoding.greedy.max_symbols\n",
        "        \n",
        "##########################################################################\n",
        "buffer_len_in_secs = chunk_len_in_secs + 2* context_len_in_secs\n"
      ],
      "metadata": {
        "id": "gF86J9Knwpe_"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Baseline: Middle Token Predictions\n",
        "\n",
        "Now compute the transcriptions over the data subset using the baseline algorithm - `Middle Token`. "
      ],
      "metadata": {
        "id": "C1s93TbcwZNt"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "asr_middle = streaming_utils.BatchedFrameASRRNNT(model, chunk_len_in_secs, buffer_len_in_secs,\n",
        "                                                 batch_size=batch_size, max_steps_per_timestep=max_steps_per_timestep)"
      ],
      "metadata": {
        "id": "PsqjMkeEu4oK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "middle_transcripts = transcribe_buffers(asr_middle, audio_filepaths, chunk_len_in_secs, buffer_len_in_secs, model_stride)"
      ],
      "metadata": {
        "id": "sNQNDjroxWb8"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "from nemo.collections.asr.metrics.wer import word_error_rate\n",
        "\n",
        "wer_middle = word_error_rate(middle_transcripts, ground_texts, use_cer=False)\n",
        "print(\"Middle token algorithm WER :\", wer_middle)"
      ],
      "metadata": {
        "id": "ENGTX70QzcrB"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## LCS Merge Predictions\n",
        "\n",
        "Next, let us compute the transcriptions over the data subset using the `LCS Merge` algorithm."
      ],
      "metadata": {
        "id": "Z3hCweGDy12t"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "asr_lcs = LongestCommonSubsequenceBatchedFrameASRRNNT(model, chunk_len_in_secs, buffer_len_in_secs,\n",
        "                                                      batch_size=batch_size, max_steps_per_timestep=max_steps_per_timestep,\n",
        "                                                      alignment_basepath=lcs_alignments_path)"
      ],
      "metadata": {
        "id": "E7DBDeBPx4cJ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "lcs_transcripts = transcribe_buffers(asr_lcs, audio_filepaths, chunk_len_in_secs, buffer_len_in_secs, model_stride)"
      ],
      "metadata": {
        "id": "BQo9TNSyzPfv"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "wer_lcs = word_error_rate(lcs_transcripts, ground_texts, use_cer=False)\n",
        "print(\"LCS algorithm WER :\", wer_lcs)"
      ],
      "metadata": {
        "id": "IXW6I3hDzT6I"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Compare the text predictions from the two merge algorithms\n",
        "\n",
        "Depending on the data subset chosen (or randomly sampled), the WER for this algorithm may be higher or lower than the baseline. Note that if you select all the samples in the dataset, then the WER of this method is slightly higher than the baseline.\n",
        "\n",
        "We will do a more in-depth analysis of the failure cases below."
      ],
      "metadata": {
        "id": "MjGfb1x00egs"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def compare_algorithms(ground_truth, middle_transcripts, lcs_transcripts, use_cer=False):\n",
        "  worse = []\n",
        "  better = []\n",
        "  same = []\n",
        "\n",
        "  for idx, (ground_text, middle_data, lcs_data) in enumerate(zip(ground_truth, middle_transcripts, lcs_transcripts)):\n",
        "      middle_wer = word_error_rate([middle_data], [ground_text], use_cer=use_cer)\n",
        "      lcs_wer = word_error_rate([lcs_data], [ground_text], use_cer=use_cer)\n",
        "\n",
        "      if middle_wer < lcs_wer:\n",
        "          worse.append((idx, ground_text, middle_data, lcs_data))\n",
        "\n",
        "      elif middle_wer > lcs_wer:\n",
        "          better.append((idx, ground_text, middle_data, lcs_data))\n",
        "      \n",
        "      else:\n",
        "          same.append((idx, ground_text, middle_data, lcs_data))\n",
        "  \n",
        "  print(\"Number of samples where both algorithms obtained same WER :\", len(same))\n",
        "  print(\"Number of samples LCS merge was better than middle ground :\", len(better))\n",
        "  print(\"Number of samples LCS merge was worse than middle ground  :\", len(worse))\n",
        "  return same, better, worse"
      ],
      "metadata": {
        "id": "80NvUa1Y0dk7"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "both_same, lcs_better, lcs_worse = compare_algorithms(ground_texts, middle_transcripts, lcs_transcripts, use_cer=False)"
      ],
      "metadata": {
        "id": "A-NIFnjo0KB5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# EXTRA: Compare the alignment matrices of LCS\n",
        "\n",
        "Over the entire dataset, there would be some samples where the `LCS Merge` algorithm did better than the `Middle Token` algorithm and vice-versa. Below, we will take a sample-level look at such cases, and since the `LCS Merge` algorithm is an alignment-based technique, we can visualize the alignment itself and determine what cases it failed and the source of the error in the alignment itself.\n"
      ],
      "metadata": {
        "id": "awZNviRC5C-O"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title LCS Alignment helper functions\n",
        "\n",
        "from torch.cuda import stream\n",
        "import torch\n",
        "import glob\n",
        "\n",
        "def try_load_alignments(alignmen_dir, idx):\n",
        "    basepath = os.path.abspath(alignmen_dir)\n",
        "    sample_path = os.path.join(basepath, str(idx))\n",
        "    \n",
        "    files = list(glob.glob(f\"{sample_path}/*.pt\"))\n",
        "    alignments = []\n",
        "    if len(files) > 0:\n",
        "        print(f\"Found {len(files)} alignments\")\n",
        "        for i in range(1, len(files) + 1):\n",
        "            path = os.path.join(sample_path, f\"alignment_{i}.pt\")\n",
        "            alignments.append(torch.load(path))\n",
        "    \n",
        "    return alignments\n",
        "\n",
        "def extract_alignments(alignments):\n",
        "    all_alignments = []\n",
        "    for data in alignments:\n",
        "        all_alignments.append(data['alignment'])\n",
        "    \n",
        "    return all_alignments\n",
        "\n",
        "def find_first_sample_with_alignment(alignment_dir, samples, start_idx: int = 0):\n",
        "    for idx in range(start_idx, len(samples)):\n",
        "        sample = samples[idx]\n",
        "        alignments = try_load_alignments(alignment_dir, sample[0])\n",
        "        if len(alignments) > 0:\n",
        "            return idx\n",
        "\n",
        "def print_alignment(alignment):\n",
        "    m = len(alignment)\n",
        "    if m > 0:\n",
        "        streaming_utils.print_alignment(alignment)\n",
        "\n",
        "def greedy_decode(asr_model, preds):\n",
        "    decoded_prediction = [p for p in preds]\n",
        "    hypothesis = asr_model.tokenizer.ids_to_text(decoded_prediction)\n",
        "    hyp_subwords = asr_model.tokenizer.ids_to_tokens(decoded_prediction)\n",
        "    return hypothesis, hyp_subwords\n",
        "\n",
        "def display_alignment_merge(alignment_path, sample, \n",
        "                            print_xy_token_ids: bool = False,\n",
        "                            print_xy_text: bool = True,\n",
        "                            print_alignments: bool = True,\n",
        "                            max_steps_per_timestep: int = None):\n",
        "\n",
        "  model_stride_in_secs = model.cfg.preprocessor.window_stride * model_stride\n",
        "  lcs_delay = math.floor(((buffer_len_in_secs - chunk_len_in_secs)) / model_stride_in_secs)\n",
        "  if max_steps_per_timestep is None:\n",
        "    max_steps_per_timestep = model.cfg.decoding.greedy.max_symbols\n",
        "\n",
        "  alignments_meta = try_load_alignments(alignment_path, sample[0])\n",
        "  alignments = extract_alignments(alignments_meta)\n",
        "\n",
        "  print(\"Sample Meta Info\")\n",
        "  print()\n",
        "  if print_xy_token_ids:\n",
        "    for idx in range(len(alignments_meta)):\n",
        "      print(\"X\", alignments_meta[idx]['X'])\n",
        "      print(\"Y\", alignments_meta[idx]['Y'])\n",
        "      print()\n",
        "    print()\n",
        "\n",
        "  if print_xy_text:\n",
        "    for idx in range(len(alignments_meta)):\n",
        "      x_text, x_subwords = greedy_decode(model, alignments_meta[idx]['X'])\n",
        "      y_text, y_subwords = greedy_decode(model, alignments_meta[idx]['Y'])\n",
        "      \n",
        "      X = alignments_meta[idx]['X'].copy()\n",
        "      Y = alignments_meta[idx]['Y'].copy()\n",
        "      search_size = int(lcs_delay * max_steps_per_timestep)\n",
        "\n",
        "      result = streaming_utils.lcs_alignment_merge_buffer(X, Y, lcs_delay, model, max_steps_per_timestep)\n",
        "      result, _ = greedy_decode(model, result)\n",
        "\n",
        "      print(\"Alignment step :\", idx)\n",
        "      print(\"Is there perfect alignment match for merge :\", alignments_meta[idx]['is_complete_merge']) \n",
        "      print()\n",
        "      print(\"Ground truth :\", sample[1])\n",
        "      print(\"Merge Result :\", result)\n",
        "      print(\"X text       :\", x_text)\n",
        "      print(\"Y text       :\", y_text)\n",
        "      print(\"Slice index  :\", alignments_meta[idx]['slice_idx'][1:], \"(start index, slice length in subword tokens)\")\n",
        "      print()\n",
        "\n",
        "      if print_alignments:\n",
        "        print_alignment(alignments[idx][-search_size:])\n",
        "        print()\n",
        "      print()\n",
        "    print()\n",
        "\n",
        "        "
      ],
      "metadata": {
        "cellView": "form",
        "id": "SiW4xw424lB1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Worse alignment\n",
        "\n",
        "Let us search for a sample where the `LCS Merge` did worse than the `Middle Token` algorithm. \n",
        "\n",
        "Such cases are necessary to analyze because it is visually apparent where the alignment went wrong. We can determine if there could be an extension to this algorithm to further improve such cases.\n"
      ],
      "metadata": {
        "id": "_DEYtkP46Srw"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "worse_idx = find_first_sample_with_alignment(lcs_alignments_path, lcs_worse, start_idx=0)\n",
        "worse_sample = lcs_worse[worse_idx]\n",
        "\n",
        "print(\"A sample where LCS did worse than Middle Token merge algorithm :\")\n",
        "print(\"The texts are structured as (Ground Truth, Middle Token, LCS Merge)\")\n",
        "worse_sample"
      ],
      "metadata": {
        "id": "rt7c-qoH5a30"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "display_alignment_merge(lcs_alignments_path, worse_sample, print_xy_token_ids=False)"
      ],
      "metadata": {
        "id": "_wBepfcH7kAK"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Better alignment\n",
        "\n",
        "Next, let us search for a sample where the `LCS Merge` did better than the `Middle Token` algorithm. \n",
        "\n",
        "Such cases are also essential to analyze because it is visually apparent where the alignment was better. We can determine if we can improve the `Middle Token` algorithm."
      ],
      "metadata": {
        "id": "Z-xHYGIEJXBx"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "better_idx = find_first_sample_with_alignment(lcs_alignments_path, lcs_better, start_idx=0)\n",
        "better_sample = lcs_better[better_idx]\n",
        "\n",
        "print(\"A sample where LCS did better than Middle Token merge algorithm :\")\n",
        "print(\"The texts are structured as (Ground Truth, Middle Token, LCS Merge)\")\n",
        "better_sample"
      ],
      "metadata": {
        "id": "AHBx3QpQE5OX"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "display_alignment_merge(lcs_alignments_path, better_sample)"
      ],
      "metadata": {
        "id": "urjYWVGfJhlU"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Final notes\n",
        "\n",
        "Following the [Buffered Transducer Inference](https://github.com/NVIDIA/NeMo/blob/stable/tutorials/asr/Buffered_Transducer_Inference.ipynb) tutorial and designing a token merge algorithm that can be a simple extension to the baseline `Middle Token` algorithm, we see that there are cases where both algorithms have their uses. \n",
        "\n",
        "To expand our research effort on developing more sophisticated streaming / buffered transducer inference methods, we encourage the users to try these algorithms in script format for efficient inference on large datasets - available at [ASR Chunked Streaming Inference](https://github.com/NVIDIA/NeMo/blob/stable/examples/asr/asr_chunked_inference/rnnt/speech_to_text_buffered_infer_rnnt.py).\n"
      ],
      "metadata": {
        "id": "GRFifXuROpzg"
      }
    }
  ]
}
